package com.wh.message.sms.service.impl;

import com.wh.common.util.Result;
import com.wh.message.sms.in.SendSmsIn;
import com.wh.message.sms.service.ChuangLanMassageService;
import com.wh.message.sms.utils.SmsConfig;
import com.wh.message.utils.HttpPostUtil;
import com.wh.message.utils.ValidatorFactoryUtil;
import com.wh.msg.ResultCode;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;



/**
 * 创蓝短信发送消费者
 * @author 谢泽鹏
 * @version V1.0
 * @Package com.wh.message.mongo.service.impl
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
public class ChuangLanMessageServiceImpl implements ChuangLanMassageService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 是否开启短信
     */
    @Value("#{settings['chuanglan.isOpen']}")
    private String isOpen;

    /**
     * 短信配置对象
     */
    private SmsConfig smsConfig;

    /**
     * 加载smsConfig
     * @param smsConfig
     */
    public void setSmsConfig(SmsConfig smsConfig) {
        this.smsConfig = smsConfig;
    }

    @Override
    public Result sendSms(SendSmsIn sendSmsIn) {
        logger.info("sendSms创蓝短信-->>开始");
        logger.info("sendSms创蓝短信-->>sendSmsIn = {}", JSONObject.fromObject(sendSmsIn).toString());
        logger.info("sendSms创蓝短信-->>smsConfig = {}", JSONObject.fromObject(smsConfig).toString());
        Result result = new Result();
        try {
            result = ValidatorFactoryUtil.validate(sendSmsIn);
            if(!ResultCode.RES_OK.equals(result.getResCode())){
                logger.info("sendSms创蓝短信-->>参数校验不通过-->>result = {}", result);
                return result;
            }
            //获取短信签名
            String autograph = smsConfig.getAutograph();
            //获取短信内容
            String content = sendSmsIn.getContent();
            //判断短信签名是否在前--》动态设置短信内容
            if (autograph != null && autograph.length() > 0) {
                if (smsConfig.isTop()) {
                    content = autograph + content;
                } else {
                    content = content + autograph;
                }
            }

            //构建请求参数
            Map<String, Object> map = new HashMap<>();
            map.put("un", smsConfig.getAccount());
            map.put("pw", smsConfig.getPassword());
            map.put("phone", sendSmsIn.getPhone());
            map.put("msg", sendSmsIn.getContent());
            map.put("rd", smsConfig.getNeedstatus());
            map.put("ex", smsConfig.getSmformat());
            String str = null;
            JSONObject jsonObject = null;
            jsonObject = JSONObject.fromObject(sendSmsIn);
            String key = null;

            HttpPostUtil httpPostUtil = new HttpPostUtil();
            if(!Boolean.parseBoolean(isOpen)){
                str = System.currentTimeMillis()+",0\n" + UUID.randomUUID().toString();
            }else{
                str = httpPostUtil.httpPost(smsConfig.getSmsUrl(), map);
            }
            logger.info("sendSms创蓝短信-->>sendSms创蓝短信,接收第三方返回值为：{}", str);
            if (null != str && str.split(",").length > 0) {
                str = str.replaceAll("\n", ",");
                key = str.split(",")[1];
                jsonObject.put("key", key);
                jsonObject.put("time", str.split(",")[0]);
                if ("0".equals(key)) {
                    jsonObject.put("messageid", str.split(",")[2]);
                    result.setResCode(ResultCode.RES_OK);
                } else {
                    result.setResCode(ResultCode.RES_NO);
                }
            } else {
                result.setResCode(ResultCode.RES_NO);
            }
            result.setResult(key);
            logger.info("sendSms创蓝短信-->>sendSms创蓝短信,成功");
        }catch (Exception e){
            logger.error("sendSms创蓝短信-->>sendSms创蓝短信-->>出现异常msg={}",e.getMessage());
            e.printStackTrace();
            result.setResCode(ResultCode.RES_ERR);
            result.setResult(e.getMessage());
        }
            logger.info("sendSms创蓝短信-->>结束");
            return result;
    }




}
